/**
addjs
@author  []
@fileoverview a javascript combine dev tools
@vserion 0.0.16
**/

!function(win, doc) {
    function checkRe(regExp) {
        return regExp.test(location.search);
    }
    function isDebug() {
        return checkRe(/debug/);
    }
    function isSass() {
        return checkRe(/sass/);
    }
    function isEs6() {
        return checkRe(/es6/);
    }
    function makeUrl(url) {
        var rs,
        	config = addjs.config,
			checkDebug = isDebug();
        
		if (checkDebug && config.debugMap && config.debugMap[url]) {
			rs = config.debugServer + config.debugMap[url];
			rs = isSass() ? rs + "&sass=1" : rs;
			rs = isEs6() ? rs + "&es6=1" : rs;
		} else {
			rs = url;
		}

		return rs;
    }
    function loadScript(url, callback) {
        var urls = ["<script", "onError=\"addjsCollectErr && addjsCollectErr('" + url + "')\""];
        if (callback) {
			urls.push("onload=\"addjsTimeline && addjsTimeline.done('" + callback + "')\"");
		}
        urls.push('src="' + url + '"');
        urls.push("></script>");
        doc.write(urls.join(" "));
    }
    function loadCss(url, callback) {
        var urls = ["<link", "onError=\"addjsCollectErr && addjsCollectErr('" + url + "')\""];
        if (callback) {
			urls.push("onload=\"addjsTimeline&&addjsTimeline.done('" + callback + "')\"");
		}
        urls.push('href="' + url + '"');
        urls.push('rel="stylesheet">');
        doc.write(urls.join(" "));
    }
    function doLoadFile(callback) {
        if (addjs.config) {
			callback(addjs.config);
		} else {
			if (addjsTimeline) {
				addjsTimeline.setStart("addjs_config.js")
			}
			loadScript(urlEncode(dataConfig, "t=" + dataCurrTime), "addjs_config.js");
			addjs.cbs.push(callback);
		}
    }
    function urlEncode(url, params) {
        return url + (url.indexOf("?") !== -1 ? "&": "?") + params;
    }
    function loadFile(url, callback) {
        doLoadFile(function(config) {
            url = makeUrl(url);
            url = isDebug() ? url : urlEncode(url, "v=" + config.version);

            callback(url);
        });
    }

    var addjs, els = doc.getElementsByTagName("script"),
		len = els.length,
		elem = els[len - 1],
		dataConfig = elem.getAttribute("data-config"),
		dataConfigCache = elem.getAttribute("data-config-cache"),
		dataCurrTime = parseInt(Date.now() / (1000 * 60 * parseInt(dataConfigCache, 10)), 10);

    win.addjsTimeline = {
        _gQueue: {},
        setStart: function(url) {
            try {
                var currTime = Date.now();
                if (this._gQueue.hasOwnProperty(url)) {
					this._gQueue[url].push(currTime);
				} else {
					this._gQueue[url] = [currTime];
				}
            } catch(e) {
                console.log(e);
            }
        },
        done: function(callback) {
            var currTime, cbs, collectObj;
            try {
                if (this._gQueue.hasOwnProperty(callback)) {
					currTime = Date.now();
					cbs = this._gQueue[callback].map(function(otherTime) {
						return currTime - otherTime;
					}).join(",");

					this._gQueue[callback] = null;
					collectObj = {};
					collectObj[callback + "_cost"] = cbs;
					
					if (typeof(win.collect) == "function") {
						win.collect.add(collectObj);
					} else {
						win.gCollectLive = win.gCollectLive || [];
						win.gCollectLive.push(collectObj);
					}
				}
            } catch(e) {
                console.log(e);
            }
        }
    };
    win.addjsCollectErr = function(url) {
        try {
            var urls = url.split("/");
            url = urls.pop ? urls.pop() : urls[urls.length - 1];
            url = url.replace(/\?.*$/, "");

            if (typeof(win.collect) == "function") {
				win.collect.add({
					loadFail: url
				});
			} else {
				win.gCollectLive = win.gCollectLive || [];
				win.gCollectLive.push({
					loadFail: url
				});
			}
        } catch(e) {
            console.log(e);
        }
    };
    addjs = {
        _debug: false,
        _configLoaded: false,
        cbs: [],
        css: function(url) {
            loadFile(url, loadCss);
        },
        js: function(url) {
            loadFile(url, loadScript);
        },
        setConfig: function(config) {
            var _this = this;
            if (!config.version) {
				throw new Error("must have a version");
			}            
			if (!config.debugServer) {
				config.debugServer = "http://127.0.0.1:7575/combine?filename=";
            }

			this.config = config;
            this.cbs.forEach(function(item) {
                if (!item.exec) {
					item(_this.config);
					item.exec = true;
				}
            });
        }
    };

    win.addjs = addjs;

	if (!win.globalConfig) {
		win.globalConfig = {
			startTime: Date.now()
		}
	}
} (window, document);
